from info.models import User, News
from info.moduls.index import index_bp
from info import redis_store, constants
from flask import render_template, current_app, session, jsonify
from flask import Blueprint
# 模板渲染方法

from info.response_code import RET


# 3.使用蓝图对象装饰视图函数
@index_bp.route('/')
def index():
    # ----------------------1.查询用户基本信息展示----------------------

    # 1.根据session获取用户user_id
    user_id = session.get("user_id")

    user = None
    # 先定义，再使用 否则：local variable 'user_dict' referenced before assignment
    user_dict = None

    if user_id:
        # 2.根据user_id查询用户对象
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)
            return "查询用户对象异常"

        # 3.将用户对象转换成字典
        """
        if user:
            user_dict = user.to_dict()
        """
        user_dict = user.to_dict() if user else None

    # ----------------------2.查询新闻排行列表数据----------------------
    # order_by将新闻的浏览量排序
    try:
        rank_news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询点击排行异常")

    rank_dict_list = []
    for news in rank_news_list if rank_news_list else []:
        rank_dict_list.append(news.to_dict())

    # 返回模板的同时将查询到的数据一并返回
    # 组织返回数据
    data = {
        "user_info": user_dict,
        "click_news_list": rank_dict_list

    }
    return render_template("news/index.html", data=data)


@index_bp.route('/favicon.ico')
def get_favicon():
    return current_app.send_static_file("news/favicon.ico")
